//用户登录的逻辑
const sqlConn2136 = require('../utils/sqlserver2136')
const jwt = require('jsonwebtoken')

//用户登录
exports.login = async (req, res) => {
   const { userid, password } = req.body; 
   if (!userid || !password) {
      return res.status(400).json({ code: 400, message: '用户ID和密码不能为空' });
   }
   const params = { userid, password }
   const sqlstr = `select * from Users where UserID='${userid}'`   
   const result = await sqlConn2136(sqlstr, params)
   // console.log(result);
   if (result.recordset.length > 0) {
      if (result.recordset[0].PassWord === password) {
         const token = generateToken({
            userid,           
         })
         res.send({
            code: 200,
            message: '登录成功!',
            uid:[6447,5071],
            uname:['张三','李四'],
            token
         })
      }else{
         res.send({ 
            code: 400, 
            message: '密码错误' 
         });
      } 
   } else {
      res.send({
         code: 400,
         message: '用户不存在!',     
      })
   }
}

//更新密码
exports.updatePwd=async (req,res)=>{
   const {userid,password,newpassword,token}=req.body;
   //验证token
   if(!token){
      return res.status(400).json({code:400,message:'token不能为空'});
   }
   try{
      const decoded=jwt.verify(token,'mysecretkey');
   }catch(err){
      return res.status(400).json({code:400,message:'token无效'});
   }

   if(!userid||!password||!newpassword){
      return res.status(400).json({code:400,message:'用户ID、密码和新密码不能为空'});
   }
   const sqlstr=`update Users set PassWord='${newpassword}' where UserID='${userid}' and PassWord='${password}'`
   const result=await sqlConn2136(sqlstr);
   // console.log(result);
   if(result.rowsAffected[0]>0){
      res.send({
         code:200,
         message:'密码更新成功!',
      })
   }else{
      res.send({
         code:400,
         message:'密码更新失败!',
      })
   }
}

//封装生成token函数
const generateToken=(user)=>{
   return jwt.sign(user,'mysecretkey',{expiresIn:'60s'})//10s,10m,1h
}

// module.exports = {
//    login,
//    updatePwd
// }